'use client'
import Link from 'next/link'
import {motion} from 'motion/react'
import {fadeInUp, scaleIn} from '../shared/animations'
import {useState, useEffect} from 'react'
import '../shared/styles.css'
import Image from 'next/image'
import {Button} from '@/ui'
import TimeAndLocation from '../shared/time-and-location'
import {LiveWorkshop} from '@/types'
import Logo from './hero-logo'

export interface SignUpFormRef {
  focus: () => void
}

const phrases = [
  'Master Context Engineering in',
  'Script Workflows with',
  'Automate Tasks using',
]

const flags = ['🇪🇺', '🇬🇧', '🇫🇷', '🇩🇪', '🇪🇸', '🇳🇱', '🇵🇹', '🇧🇪']

function parseUtcOffsetToHours(utcOffset: string): number | null {
  // Supports "-05:00", "+5", "UTC-7", "UTC+07:30", etc.
  const match = utcOffset
    .trim()
    .match(/^(?:UTC)?\s*([+-])?(\d{1,2})(?::?(\d{2}))?$/i)
  if (!match) {
    console.error(`Invalid utcOffset format: ${utcOffset}`)
    return null
  }

  const sign = match[1] === '-' ? -1 : 1
  const hours = parseInt(match[2], 10)
  const minutes = parseInt(match[3] || '0', 10)

  return sign * (hours + minutes / 60)
}

function parseDateParts(dateStr: string) {
  const isoMatch = dateStr.match(/^(\d{4})-(\d{2})-(\d{2})$/)
  if (isoMatch) {
    return {
      year: parseInt(isoMatch[1], 10),
      month: parseInt(isoMatch[2], 10),
      day: parseInt(isoMatch[3], 10),
    }
  }

  const longMatch = dateStr.match(/^([A-Za-z]+)\s+(\d{1,2}),\s*(\d{4})$/)
  if (longMatch) {
    const monthNames = [
      'january',
      'february',
      'march',
      'april',
      'may',
      'june',
      'july',
      'august',
      'september',
      'october',
      'november',
      'december',
    ]
    const monthIndex = monthNames.indexOf(longMatch[1].toLowerCase())
    if (monthIndex >= 0) {
      return {
        year: parseInt(longMatch[3], 10),
        month: monthIndex + 1,
        day: parseInt(longMatch[2], 10),
      }
    }
  }

  console.error('Could not parse date string format:', dateStr)
  return null
}

function mapTimeZoneLabelToIana(timeZone?: string): string | null {
  if (!timeZone) return null
  const normalized = timeZone.replace(/[()]/g, '').trim()
  if (normalized.includes('/')) return normalized // already IANA

  const lower = normalized.toLowerCase()
  const mapping: Record<string, string> = {
    pdt: 'America/Los_Angeles',
    pst: 'America/Los_Angeles',
    pt: 'America/Los_Angeles',
    edt: 'America/New_York',
    est: 'America/New_York',
    et: 'America/New_York',
    cdt: 'America/Chicago',
    cst: 'America/Chicago',
    ct: 'America/Chicago',
    mdt: 'America/Denver',
    mst: 'America/Denver',
    mt: 'America/Denver',
    bst: 'Europe/London',
    gmt: 'Europe/London',
    cet: 'Europe/Paris',
    cest: 'Europe/Paris',
  }

  return mapping[lower] || null
}

function parseOffsetFromTzName(tzName?: string): number | null {
  if (!tzName) return null
  const match = tzName.match(/(?:GMT|UTC)?\s*([+-])(\d{1,2})(?::(\d{2}))?/)
  if (!match) return null

  const sign = match[1] === '-' ? -1 : 1
  const hours = parseInt(match[2], 10)
  const minutes = parseInt(match[3] || '0', 10)

  return sign * (hours + minutes / 60)
}

function deriveOffsetHoursFromIana(
  dateParts: {year: number; month: number; day: number},
  timeParts: {hours: number; minutes: number},
  ianaTimeZone: string,
): number | null {
  try {
    const utcDate = new Date(
      Date.UTC(
        dateParts.year,
        dateParts.month - 1,
        dateParts.day,
        timeParts.hours,
        timeParts.minutes,
      ),
    )

    const baseOptions = {
      timeZone: ianaTimeZone,
      hour12: false,
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
    } as const

    const tzNamesToTry: Array<Intl.DateTimeFormatOptions['timeZoneName']> = [
      'shortOffset',
      'longOffset',
      'short',
      'long',
    ]

    for (const tzNameOpt of tzNamesToTry) {
      const formatter = new Intl.DateTimeFormat('en-US', {
        ...baseOptions,
        timeZoneName: tzNameOpt,
      })
      const parts = formatter.formatToParts(utcDate)
      const tzName = parts.find((p) => p.type === 'timeZoneName')?.value
      const parsed = parseOffsetFromTzName(tzName)
      if (parsed !== null) return parsed
    }

    return null
  } catch (error) {
    console.error('Error deriving offset from IANA timezone:', error)
    return null
  }
}

// Helper function to parse date/time string with a specific offset
// Supports "YYYY-MM-DD" and "Month Day, Year" date strings
// Assumes timeStr is like "H:mm AM/PM"
// Assumes inputTimeZoneOffset is hours difference from UTC (e.g. -5 for UTC-5)
export function parseDateTimeWithOffset(
  dateStr: string,
  timeStr: string,
  inputTimeZoneOffset: number,
  timeZoneLabel?: string,
): Date | null {
  const dateParts = parseDateParts(dateStr)
  if (!dateParts) return null

  const timeMatch = timeStr.match(/(\d{1,2}):(\d{2})\s*(AM|PM)/i)
  if (!timeMatch) {
    console.error('Could not parse time string format:', timeStr)
    return null
  }

  let hours = parseInt(timeMatch[1], 10)
  const minutes = parseInt(timeMatch[2], 10)
  const ampm = timeMatch[3].toUpperCase()

  if (ampm === 'PM' && hours < 12) hours += 12
  if (ampm === 'AM' && hours === 12) hours = 0

  const ianaTimeZone = mapTimeZoneLabelToIana(timeZoneLabel)
  const offsetFromIana = ianaTimeZone
    ? deriveOffsetHoursFromIana(
        dateParts,
        {hours, minutes},
        ianaTimeZone,
      )
    : null
  const effectiveOffset =
    offsetFromIana !== null ? offsetFromIana : inputTimeZoneOffset

  const offsetSign = effectiveOffset >= 0 ? '+' : '-'
  const absOffsetHours = Math.abs(Math.trunc(effectiveOffset))
  const absOffsetMinutes = Math.abs(Math.round((effectiveOffset % 1) * 60))
  const formattedOffset = `${offsetSign}${String(absOffsetHours).padStart(
    2,
    '0',
  )}:${String(absOffsetMinutes).padStart(2, '0')}`

  const isoString = `${String(dateParts.year).padStart(4, '0')}-${String(
    dateParts.month,
  ).padStart(2, '0')}-${String(dateParts.day).padStart(2, '0')}T${String(
    hours,
  ).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:00${formattedOffset}`

  try {
    const finalDate = new Date(isoString)
    if (isNaN(finalDate.getTime())) {
      console.error(
        'Failed to create final Date object from ISO string:',
        isoString,
      )
      return null
    }
    return finalDate
  } catch (e) {
    console.error('Error creating final Date object:', e)
    return null
  }
}

// Helper function to format Date into "H:mm A" in a specific timezone
export function formatTimeInTimeZone(date: Date, timeZone: string): string {
  try {
    return date.toLocaleTimeString('en-US', {
      timeZone: timeZone,
      hour: 'numeric',
      minute: '2-digit',
      hour12: true,
    })
  } catch (e) {
    console.error(`Error formatting time for timezone ${timeZone}:`, e)
    // Fallback or default value if timezone is invalid
    return date.toLocaleTimeString('en-US', {
      hour: 'numeric',
      minute: '2-digit',
      hour12: true,
    })
  }
}

const AnimatedPhrase = ({text}: {text: string}) => (
  <motion.span
    key={text}
    initial={{opacity: 0, y: -20}}
    animate={{opacity: [0, 1, 1, 0], y: 0}}
    exit={{opacity: 0, y: 20}}
    transition={{duration: 2.5, times: [0, 0.1, 0.9, 1]}}
    className="absolute left-0 right-0"
  >
    {text}
  </motion.span>
)

function scrollToSignup(
  e: React.MouseEvent<HTMLAnchorElement>,
  formRef: React.RefObject<SignUpFormRef | null>,
) {
  e.preventDefault()
  document.querySelector('#signup')?.scrollIntoView({behavior: 'smooth'})
  setTimeout(() => {
    formRef.current?.focus()
  }, 500)
}

interface HeroProps {
  formRef: React.RefObject<SignUpFormRef | null>
  saleisActive: boolean
  workshop: LiveWorkshop
}

export default function Hero({formRef, saleisActive, workshop}: HeroProps) {
  const [phraseIndex, setPhraseIndex] = useState(0)
  const [flagIndex, setFlagIndex] = useState(0)

  useEffect(() => {
    const phraseTimer = setInterval(() => {
      setPhraseIndex((current) => (current + 1) % phrases.length)
    }, 3000)
    const flagTimer = setInterval(() => {
      setFlagIndex((current) => (current + 1) % flags.length)
    }, 2000)
    return () => {
      clearInterval(phraseTimer)
      clearInterval(flagTimer)
    }
  }, [])

  // Calculate European times
  const offsetHours = workshop?.utcOffset
    ? parseUtcOffsetToHours(workshop.utcOffset)
    : null
  const workshopDateObj = workshop
    ? parseDateTimeWithOffset(
        workshop.date,
        workshop.startTime,
        offsetHours ?? 0,
        workshop.timeZone,
      )
    : null
  const londonTime = workshopDateObj
    ? formatTimeInTimeZone(workshopDateObj, 'Europe/London')
    : 'Error'
  const parisBerlinTime = workshopDateObj
    ? formatTimeInTimeZone(workshopDateObj, 'Europe/Paris')
    : 'Error'

  return (
    <section className="sm:py-12 py-8 bg-white dark:bg-gray-900 md:py-10 text-center  overflow-hidden max-w-3xl mx-auto">
      <div className="absolute inset-0 pattern-dots" />
      <div
        aria-hidden="true"
        className="absolute inset-0 w-full h-full bg-gradient-to-b dark:from-gray-900/90 dark:to-gray-900/70 from-gray-50 to-transparent"
      />
      <motion.div {...scaleIn} className="relative px-6 mt-16">
        {/* <Image
          className="mx-auto mb-5 sm:px-0 px-10 absolute -top-32 "
          quality={100}
          src="https://res.cloudinary.com/dg3gyk0gu/image/upload/v1752612749/claude-code-hero-image_yoyhxp.png"
          alt="Cursor IDE"
          width={4016 / 3}
          height={2391 / 3}
        /> */}
        <Logo />
        <motion.h1
          {...fadeInUp}
          className="lg:text-5xl sm:text-4xl text-xl flex flex-col relative mb-6 font-extrabold tracking-tight dark:text-white leading-tight"
        >
          Transform into a Claude Code Power User
        </motion.h1>

        <motion.p
          {...fadeInUp}
          transition={{delay: 0.1}}
          className="relative mb-8 sm:text-lg md:text-lg dark:text-gray-200 text-gray-700 max-w-3xl mx-auto leading-relaxed "
        >
          Join{' '}
          <span className="text-gray-900 pl-2 inline-flex items-baseline md:gap-2 gap-1 dark:text-white font-medium">
            <Image
              src={
                'https://res.cloudinary.com/dg3gyk0gu/image/upload/v1683164538/assets/john.webp'
              }
              alt="John Lindquist"
              width={40}
              height={40}
              className="rounded-full relative md:translate-y-3 translate-y-2 md:w-10 w-7"
            />{' '}
            John Lindquist
          </span>
          , founder of egghead.io, for an immersive workshop designed to teach
          you how to effectively use Claude in your development workflow. You'll
          go beyond simple prompting and master key techniques like context
          engineering, scripting with the SDK, Claude hooks, and MCPs. By the
          end, you'll confidently apply AI for targeted refactors, feature
          implementation, and bug fixes.
        </motion.p>

        <motion.div
          {...fadeInUp}
          transition={{delay: 0.3, type: 'spring', stiffness: 200}}
          className="relative"
        >
          <div className="mt-12 flex flex-col gap-4 justify-center items-center">
            {saleisActive && workshop && (
              <div className="">
                <TimeAndLocation
                  date={workshop.date}
                  startTime={workshop.startTime}
                  timeZone={workshop.timeZone}
                  endTime={workshop.endTime}
                  iconSize={6}
                  className="text-lg gap-2 text-muted-foreground flex md:flex-row md:gap-6"
                />
                {workshop.isEuFriendly && (
                  <div className="relative mb-8 max-w-md mx-auto">
                    <div className="bg-gradient-to-r from-purple-600 to-blue-600 rounded-lg p-4 shadow-lg transform rotate-0 hover:rotate-1 transition-transform">
                      <div className="flex items-center gap-3">
                        <div className="flex space-x-1 h-[1.5em] items-center min-w-[24px]">
                          <motion.span
                            key={flagIndex}
                            className="text-xl"
                            initial={{opacity: 0}}
                            animate={{opacity: [0, 1, 1, 0]}}
                            transition={{duration: 2, times: [0, 0.2, 0.8, 1]}}
                          >
                            {flags[flagIndex]}
                          </motion.span>
                        </div>
                        <div className="text-left">
                          <p className="font-bold text-white">
                            Europe-Friendly Time!
                          </p>
                          <p className="text-sm text-white/90">
                            That's {londonTime} in London, {parisBerlinTime} in
                            Paris & Berlin
                          </p>
                        </div>
                      </div>
                    </div>
                  </div>
                )}
              </div>
            )}
            <Button
              asChild
              size="lg"
              className=" sm:mt-5 dark:bg-white dark:text-black bg-black text-white text-lg font-semibold w-fit"
            >
              <Link href="#signup" onClick={(e) => scrollToSignup(e, formRef)}>
                Register Now
                {/* <ArrowCircleDownIcon className="group-hover:scale-105 w-8 h-8 transition-all duration-200" /> */}
              </Link>
            </Button>
          </div>
        </motion.div>
      </motion.div>
    </section>
  )
}
